package com.ls.blog.security.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.blog.DTO.UserDetailsDTO;
import com.ls.blog.entity.UserInfo;
import com.ls.blog.enums.ResultCode;
import com.ls.blog.mapper.UserInfoMapper;
import com.ls.blog.utils.JwtUtils;
import com.ls.blog.utils.R;
import com.ls.blog.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 认证成功处理
 *
 * @author 11921
 */
@Component
@Slf4j
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {

        // 生成jwt,并放到请求头中
        String token = jwtUtils.generateToken(authentication.getName());
        httpServletResponse.setHeader(jwtUtils.getHeader(), token);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        UserDetailsDTO userDetailsDTO = (UserDetailsDTO) authentication.getPrincipal();
        // 查询账号信息
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .select(UserInfo::getId, UserInfo::getEmail, UserInfo::getNickname, UserInfo::getAvatar, UserInfo::getIntro, UserInfo::getWebSite, UserInfo::getIsDisable)
                .eq(UserInfo::getId,userDetailsDTO.getId()));
        // 登录后的信息放到redis中
        redisUtil.hset("token",token,userInfo);
        httpServletResponse.getWriter().write(JSON.toJSONString(R.ok(ResultCode.LOGIN_ok,userInfo)));

    }

/*
    /**
     * 更新用户信息
     * /
    @Async
    public void updateUserInfo() {
        UserAuth userAuth = UserAuth.builder()
                .id(UserUtil.getLoginUser().getId())
                .ipAddr(UserUtil.getLoginUser().getIpAddr())
                .ipSource(UserUtil.getLoginUser().getIpSource())
                .lastLoginTime(UserUtil.getLoginUser().getLastLoginTime())
                .build();
        userAuthMapper.updateById(userAuth);
    }
*/

}
